<template>
  <div>
    <div>
      <div class="main" v-show="!rtc.joined">
        <div class="inp">
          <span>房间号：</span><input type="text" v-model="option.channel">
        </div>
        <div class="dtn">
          <button type="button" class="btn" @click="joinChannel">进入</button>
        </div>
      </div>
      <div id="view" class="view">
        <div id="local_stream" class="stream"></div>
      </div>
      <div class="out" v-show="rtc.joined">
        <button type="button" class="out-btn" @click="leave">退出</button>
      </div>
    </div>
  </div>
</template>

<script>
import AgoraRTC from "agora-rtc-sdk";
export default {
  name: "HelloWorld",
  data() {
    return {
        rtc:{
            client: '', //rtc客户端对象
            joined: false, //是否进入频道
            published: false,
            localStream: '',  
            remoteStreams: [],  
            params: {}
        },
        option:{
            appID: "915d15514a01470da2c14fa6929a77df", //声网管理平台的appid
            channel: "", //频道名，长度在 64 字节以内的字符串
            uid: Math.floor(Math.random()*1000), //用户ID  唯一，根据自己项目自定义
            token: "" //验证参数，（不做验证可以跳过）
        }
    };
  },
  created() {
    this.init();
  },
  mounted() {},
  methods: {
    init() {
      this.rtc.client = AgoraRTC.createClient({ mode: "rtc", codec: "h264" });
      this.rtc.client.init(
        this.option.appID,
        function () {
          console.log("init success");
        },
        (err) => {
          console.error(err);
        }
      );

    },
    joinChannel(){
        let _this = this
        this.rtc.client.join(this.option.token ? this.option.token : null, this.option.channel, this.option.uid ? this.option.uid : null, function (uid) {
            console.log("join channel: " + _this.option.channel + " success, uid: " + uid);
            _this.subscribed() //加入后监听其它用户加入
            _this.removed() //监听其它用户退出
            _this.rtc.joined = true
            _this.rtc.params.uid = uid;
            _this.createStream() //创建本地流
        }, function(err) {
            console.error("client join failed", err)
        })
    },
    leave(){ //离开频道
      // Leave the channel
      if(this.rtc.joined){
        var nodes = document.getElementById("view").childNodes;
        for(var i=0; i<nodes.length; i++){
          if(nodes[i].indexOf("remote")>-1){
            console.log(nodes[i])
          }
        }
        return;
      }
      let _this = this
      _this.rtc.client.leave(function () {
        // Stop playing the local stream
        _this.rtc.localStream.stop();
        // Close the local stream
        _this.rtc.localStream.close();
        // Stop playing the remote streams and remove the views
        while (_this.rtc.remoteStreams.length > 0) {
          var stream = _this.rtc.remoteStreams.shift();
          var id = stream.getId();
          stream.stop();
          document.getElementById("view").removeChild(document.getElementById("remote_video_"+id))
        }
        console.log("client leaves channel success");
      }, function (err) {
        console.log("channel leave failed");
        console.error(err);
      })
    },
    createStream(){ //创建本地流并发布
        let _this = this
        this.rtc.localStream = AgoraRTC.createStream({
            streamID: this.rtc.params.uid,
            audio: true, //打开音频
            video: true, //打开摄像头
            screen: false,
        })
        this.rtc.localStream.init(function () {
            console.log("init local stream success");
            // play stream with html element id "local_stream"
            //播放本地流
            _this.rtc.localStream.play("local_stream");
            //发布本地流
            _this.rtc.client.publish(_this.rtc.localStream, function (err) {
                console.log("publish failed");
                console.error(err);
            })
        }, function (err) {
            console.error("init local stream failed ", err);
        });
    },
    subscribed(){ //订阅并播放远程流
      let _this = this
      //监听其它用户加入频道
      this.rtc.client.on("stream-added", function (evt) {  
        var remoteStream = evt.stream;
        var id = remoteStream.getId();
        if (id !== _this.rtc.params.uid) {
          //监听到有其它用户加入频道，订阅该用户的远程流
          _this.rtc.client.subscribe(remoteStream, function (err) {
            console.log("stream subscribe failed", err);
          })
        }
        console.log('stream-added remote-uid: ', id);
      });
      //监听订阅其它用户的远程流
      this.rtc.client.on("stream-subscribed", function (evt) {
        var remoteStream = evt.stream;
        var id = remoteStream.getId();
        // Add a view for the remote stream.
        //动态添加dom节点
        _this.addView("remote_video_"+id);
        // Play the remote stream.
        //播放远程流
        remoteStream.play("remote_video_" + id);
        console.log('stream-subscribed remote-uid: ', id);
      })
    },
    //监听取消订阅
    removed(){
      this.rtc.client.on("stream-removed", function (evt) {
        var remoteStream = evt.stream;
        var id = remoteStream.getId();
        // Stop playing the remote stream.
        remoteStream.stop("remote_video_" + id);
        // Remove the view of the remote stream. 
        document.getElementById("view").removeChild(document.getElementById("remote_video_"+id))
        console.log('stream-removed remote-uid: ', id);
      })
    },
    //动态添加远程流的dom节点
    addView(id){
      var video = document.createElement("div");
      video.id = id
      video.setAttribute ("class","stream")
      document.getElementById("view").appendChild(video)
    }
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
  .stream{
    width: 47vw;
    height: 30vh;
    display: inline-block;
  }
  .view>.stream:nth-child(2n+1){
    
  }
  .view>.stream:nth-child(2n){
    float: right;
  }

  .main{
    margin-top: 50px;
    margin-left: 10px;
  }
  .inp{
    font-size: 18px;
    height: 50px;
  }
  .inp span{
    width: 30%;
  }
  .inp input{
    width: 60%;
    -webkit-appearance: none;
    background-color: #fff;
    background-image: none;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    box-sizing: border-box;
    color: #606266;
    display: inline-block;
    font-size: inherit;
    height: 40px;
    line-height: 40px;
    outline: none;
    padding: 0 15px;
    transition: border-color .2s cubic-bezier(.645,.045,.355,1);
  }
  .dtn{
    margin-top: 30px;
    width: 100%;
    text-align: center;
  }
  .btn{
    width: 150px;
    color: #fff;
    background-color: #67c23a;
    border-color: #67c23a;
    display: inline-block;
    line-height: 1;
    white-space: nowrap;
    cursor: pointer;
    border: 1px solid #dcdfe6;
    -webkit-appearance: none;
    text-align: center;
    box-sizing: border-box;
    outline: none;
    margin: 0;
    transition: .1s;
    font-weight: 500;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    padding: 10px 18px;
    font-size: 16px;
    border-radius: 4px;
  }
  .out{
    width: 100%;
    text-align: center;
    position: absolute;
    bottom: 20px;
  }
  .out-btn{
    width: 150px;
    color: #fff;
    background-color: #F56C6C;
    border-color: #F56C6C;
    display: inline-block;
    line-height: 1;
    white-space: nowrap;
    cursor: pointer;
    border: 1px solid #dcdfe6;
    -webkit-appearance: none;
    text-align: center;
    box-sizing: border-box;
    outline: none;
    margin: 0;
    transition: .1s;
    font-weight: 500;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    padding: 10px 18px;
    font-size: 16px;
    border-radius: 4px;
  }
</style>
